package com.oocl.userinfo.servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.oocl.userinfo.dao.UserDao;
import com.oocl.userinfo.dao.impl.UserDaoImpl;
import com.oocl.userinfo.pojo.User;
import com.oocl.userinfo.util.StringUtil;

public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final int SIZE_THRESHOLD = 20 * 1024;
	private final int HEADIMG_MAX_SIZE = 100 * 1024;
	private final String ERROR_MSG_KEY = "errorMsg";
	
	private UserDao userDao;
	
	public RegisterServlet() {
		userDao = new UserDaoImpl();
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String tmpdir = System.getProperty("java.io.tmpdir");
		DiskFileItemFactory factory = new DiskFileItemFactory(SIZE_THRESHOLD, new File(tmpdir));
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		List<FileItem> items = null;
		User u = new User();
		
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		
		if (items == null) {
			request.setAttribute(ERROR_MSG_KEY, "Other error!");
			request.getRequestDispatcher("error").forward(request, response);
			return;
		}
		

		for (FileItem item : items) {
			if (item.isFormField()) {
				String itemValue = item.getString("utf-8");
				if (StringUtil.isNullOrEmpty(itemValue)) {
					request.setAttribute(ERROR_MSG_KEY, item.getFieldName() + " cannot be empty!");
					request.getRequestDispatcher("error").forward(request, response);
					return;
				}

				switch (item.getFieldName()) {
				case "uname":
					u.setUname(itemValue);
					break;
				case "sal":
					try {
						u.setSal(Double.valueOf(itemValue));
					} catch (NumberFormatException e) {
						e.printStackTrace();
						request.setAttribute(ERROR_MSG_KEY, "Salary is not a valid number!");
						request.getRequestDispatcher("error").forward(request, response);
						return;
					}
					break;
				case "birth":
					try {
						u.setBirth(new SimpleDateFormat("yyyy-MM-dd").parse(itemValue));
					} catch (ParseException e) {
						e.printStackTrace();
						request.setAttribute(ERROR_MSG_KEY, "Birthday format error!");
						request.getRequestDispatcher("error").forward(request, response);
						return;
					}
					break;
				case "sex":
					u.setSex(Boolean.valueOf(itemValue));
					break;
				}
			} else {
				if (item.getSize() > HEADIMG_MAX_SIZE) {
					request.setAttribute(ERROR_MSG_KEY, "Head image should not be larger than 100KB!");
					request.getRequestDispatcher("error").forward(request, response);
					return;
				}
				
				InputStream in = item.getInputStream();
				byte[] bytes = IOUtils.toByteArray(in);
				u.setHead(bytes);
				
				in.close();
			}
		}

		userDao.addUser(u);
		response.sendRedirect("all");
	}

}
